package com.example.books.Controller;

import com.example.books.Pojo.UserDO;
import com.example.books.Service.UserService;
import com.example.books.utils.RequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@CrossOrigin //跨域
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/query")
    public List<UserDO> query( @RequestBody  Map<String,Object> map){
        return userService.query(map);
    }

    @PostMapping("/create")
    public boolean create(@RequestBody UserDO userDO){
        return userService.create(userDO);
    }

    @PostMapping("/update")
    public boolean update(@RequestBody UserDO userDO){
        return userService.update(userDO);
    }

    @PostMapping("/delete")
    public boolean delete(@RequestBody Map<String,Object> map){
        return userService.delete(map);
    }

    @PostMapping("/search")
    public List<UserDO> search(@RequestBody Map<String,Object> map){
        return userService.search(map);
    }

    @PostMapping("/upload")
    public String upload(@RequestParam("file")MultipartFile multipartFile, HttpServletRequest request)throws Exception{
        //获取原文件名
        String originalFilename=multipartFile.getOriginalFilename();
        //获取文件名后缀
        String ext=originalFilename.substring(originalFilename.lastIndexOf(".")+1,originalFilename.length());
        //新的文件名
        String newFileNamePrefix= UUID.randomUUID().toString();
        String newFileName=newFileNamePrefix+"."+ext;
        //上传到本地指定文件夹
        multipartFile.transferTo(new File("E:\\upload",newFileName));
        System.out.println(RequestUtils.getBasePath(request)+"upload/"+newFileName);
        //返回的是一个可以访问的全路径
        return RequestUtils.getBasePath(request)+"upload/"+newFileName;
    }

    @PostMapping("/uploadImg")
    public boolean uploadImg(@RequestBody Map<String,Object> map){
        System.out.println(map);
        return userService.uploadImg(map);
    }

}
